<?php
class InspectionsController extends AppController {

	var $name = 'Inspections';

	function index() {
		$this->Inspection->recursive = 0;
		$this->set('inspections', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid inspection', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('inspection', $this->Inspection->read(null, $id));
	}

	function add($id = null) {
		if (!empty($this->data)) {
			$this->data['Inspection']['date'] = date("Y-m-d", strtotime($this->data['Inspection']['date']));
			$this->Inspection->create();
			if ($this->Inspection->save($this->data)) {
				$this->Session->setFlash(__('The inspection has been saved', true));
				$this->redirect(array('controller'=>'items','action' => 'view',$this->data['Inspection']['item_id']));
			} else {
				$this->Session->setFlash(__('The inspection could not be saved. Please, try again.', true));
			}
		}
		$items = $this->Inspection->Item->find('list');
		$statuses = $this->Inspection->Status->find('list');
		$this->set(compact('items', 'statuses','id'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid inspection', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Inspection->save($this->data)) {
				$this->Session->setFlash(__('The inspection has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The inspection could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Inspection->read(null, $id);
		}
		$items = $this->Inspection->Item->find('list');
		$statuses = $this->Inspection->Status->find('list');
		$this->set(compact('items', 'statuses'));
	}

	function delete($id = null) {
		$this->Inspection->recursive = -1;
		$item = $this->Inspection->findById($id);
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for inspection', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Inspection->delete($id)) {
			$this->Session->setFlash(__('Inspection deleted', true));
			$this->redirect(array('controller'=>'items','action'=>'view',$item['Inspection']['item_id']));
		}
		$this->Session->setFlash(__('Inspection was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
